package 第三周;

/*
 * @author  YxinMiracle
 * @date  2022-04-28 9:21
 * @Gitee: https://gitee.com/yxinmiracle
 */

import java.util.ArrayList;
import java.util.List;

public class 二叉树的序列化与反序列化 {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        // 将已经树序列化为字符串
        List<String> ans = new ArrayList<>();
        dfs(ans,root);
        return String.join(",",ans); // 用逗号相隔
    }

    private void dfs(List<String> ansList,TreeNode node){
        if (node == null){
            ansList.add("null");
            return;
        }
        // 如果不是空，那么就存入数值
        ansList.add(String.valueOf(node.val));
        dfs(ansList,node.left);
        dfs(ansList,node.right);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        this.seq = data.split(",");
        cur = 0;
        return build();
    }

    private TreeNode build() {
        if (seq[cur].equals("null")){
            cur ++;
            return null;
        }
        // 如果不是空，那么就是节点
        TreeNode treeNode = new TreeNode(Integer.parseInt(seq[cur]));
        cur ++;
        treeNode.left = build();
        treeNode.right = build();
        return treeNode;
    }

    public String[] seq; // 存储节点数据
    public int cur; // 存储当前到第几个节点


}
